<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Schema;

class StationController extends Controller
{
    //设备数据对照
    public function upParam(){
        $data = DB::table('station_up_param')->orderBy('param_name','asc')->get();
        if (request()->expectsJson()  || request('from_controller')) {
            if(request()->isMethod('post')){ //添加、编辑
                $reqData = request()->only('station_name','param','param_name');
                if($id = request('id')){
                    $res = DB::table('station_up_param')->where('id',$id)->update($reqData);
                }else{
                    $exists = DB::table('station_up_param')->where(['station_name'=>$reqData['station_name'],'param'=>$reqData['param']])->exists();
                    if($exists){
                        return out(0,'参数已存在！');
                    }
                    $res = DB::table('station_up_param')->insertGetId($reqData);
                }
                return $res;
            }
            $res = [];
            foreach($data as $item){
                if($item->param_name){
                    $res[$item->station_name][] = $item;
                }
            }
            return response()->json($res);
        }
        return view('admin.station.upParam',compact('data'));
    }
    public static function dbStat() {
        $data = [
            'trace_type'  => [
                1 => '检定',
                2 => '校准',
                3 => '核查',
            ],
            'status'      => [
                1 => '合格',
                2 => '准用',
                3 => '停用',
                4 => '淘汰',
            ],
            'trace_cycle' => [
                //溯源周期key是几个月
                0  => '/',
                6  => '半年',
                12 => '一年',
                24 => '两年',
            ]
        ];
        return $data;
    }

    //工位 列表展示
    public function index(Request $request) {
        $data = [];
        $data['stat'] = self::dbStat();
        $data['list'] = DB::table('a_station')->orderBy('dev_num','asc')->get();
        return view('admin.station.index', compact('data'));
    }
    public function import(Request $request)
    {
        if ($request->hasFile('excel')) {
            $path = $request->file('excel')->getRealPath();

            // 使用PhpSpreadsheet加载Excel文件
            try {
                $spreadsheet = IOFactory::load($path);
            } catch (Exception $e) {
                dd($e->getMessage(), $e->getTraceAsString()); // Laravel 的 dump 和 die 方法，也可以换成其他日志记录方法
            }
            $worksheet = $spreadsheet->getActiveSheet();
            $data = $worksheet->toArray();

            // 移除数组中的第一个元素，因为它通常是标题行
            array_shift($data);
            // dd($data);
            $add_arr = [];
            // 处理数据，例如保存到数据库
            foreach ($data as $row) {
                // 假设第一列是用户名，第二列是邮箱
                $add_arr[] = [
                    'name'=>$row[0],
                    'fac_num'=>$row[1],
                    'spec'=>$row[2],
                    'ranges'=>$row[3],
                    'accuracy'=>$row[4]
                ];
            }
            // 这里可以添加你的保存逻辑，例如保存到数据库
            if($add_arr){
                $add = DB::table('a_station')->insert($add_arr);
                if($add){
                    return 1;
                }else{
                    return '导入失败';
                }
            }
            // dd($add_arr);
            // return '导入成功！';
        }
 
        return '未找到文件';
    }
    //设备套装组合
    public function groupIndex(Request $request) {
        $data = [];
        $list = DB::table('a_station_group as a')
            ->leftJoin('a_station as b','a.station_id','=','b.id')
            ->select('a.name','b.name as station_name','b.dev_num','a.station_id')
            ->get();
        $data['list'] = $list->groupBy('name')->toArray();
        $data['stations'] = DB::table('a_station')->select('id','name','dev_num')->get();
        return view('admin.station.group.index', compact('data'));
    }

    public function groupDel(){
        $name = request('name',0);
        if ($name) {
            $res = DB::table('a_station_group')->where('name',$name)->delete();
            return $res ? 1 : 0;
        }
        return 0;
    }

    public function groupEdit(){
        $name = request('name',0);
        $station_ids = request('station_ids',0);
        $old_station_ids = DB::table('a_station_group')->where('name',$name)->pluck('station_id')->toArray();
        $diffDels = array_diff($old_station_ids, $station_ids);
        $diffIns = array_diff($station_ids, $old_station_ids);
        DB::beginTransaction();
        try {
            //删除
            DB::table('a_station_group')->where('name',$name)->whereIn('station_id',$diffDels)->delete();
            //新增
            $in = [];
            foreach ($diffIns as $station_id) {
                $in[] = [
                    'name' => $name,
                    'station_id' => $station_id,
                ];
            }
            DB::table('a_station_group')->insert($in);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return 0;
        }
        return 1;
    }

    //工位 删除
    public function del(Request $request) {
        $id = $request->id;
        $itemIds = $request->input('ids', [])?:'';
        // dd($id,$itemIds);
        if($itemIds){
            $ids = explode(',',$itemIds);
            //  delete 返回受影响的行数
            $result = DB::table('a_station')->whereIn('id', $ids)->delete();
        }else{
            //  delete 返回受影响的行数
            $result = DB::table('a_station')->where('id', $id)->delete();
        }
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $result >= 0 ? '1' : '0';
    }

    //工位 添加
    public function add(Request $request) {
        if($request->isMethod('POST')) {
            $post_data = $request->except(['_token']);
            
            if(DB::table('a_station')->where('dev_num', $post_data['dev_num'])->exists()) {
                return '编码重复！';
            }
            $post_data = $this->editPostData($post_data);
            $result = DB::table('a_station')->insert($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '0';
        }
        else {
            $data = self::dbStat();
            $data['parents'] = $this->getPar();
            return view('admin.station.add', compact('data'));
        }
    }

    //工位 修改
    public function edit(Request $request) {
        $id = $request->id;
        if($request->isMethod('POST')) {
            if (request('ids','')) { //多选显示或隐藏中控室页面
                $ids = request('ids');
                $isHide = request('isHide');
                // dd($ids,$isHide);
                $res = DB::table('a_station')->whereIn('id',$ids)->update(['ishide'=>$isHide]);
                return $res ? 1:0;
            }
            $post_data = $request->except(['_token']);
            $where = [['id', '!=', $id], ['dev_num', '=', $post_data['dev_num']]];
            if(DB::table('a_station')->where($where)->exists()) {
                return '编码/设备编号已存在';
            }
            $post_data = $this->editPostData($post_data);
            $result = DB::table('a_station')->where('id', $id)->update($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '还没修改数据！';
        }
        else {
            //查询要修改的工位 信息
            $info = DB::table('a_station')->find($id);
            $data = self::dbStat();
            $data['parents'] = $this->getPar();
            $data['pnum'] = $info->pid == 0 ? '/' : (DB::table('a_station')->where('id',$info->pid)->value('dev_num'));
            return view('admin.station.edit', compact('info', 'data'));
        }
    }

    private function editPostData($data) {
        $data['trace_exp_date'] = $data['trace_cycle'] ? date('Y-m-d', strtotime("+{$data['trace_cycle']} months -1 days", strtotime($data['trace_date']))) : ''; //计算溯源到期日期

        if(!$data['buy_date']){
            unset($data['buy_date']);
        }
        if (!$data['trace_date']) {
            unset($data['trace_date']);
            unset($data['trace_exp_date']);
        }

        $data['pid'] = $data['pid'] == '/' ? 0 : (DB::table('a_station')->where('dev_num',$data['pid'])->value('id'));

        // $data = array_filter($data);     //去掉为空的数据
        return $data;
    }

    //获取pid为0的数据
    private function getPar() {
        $parents = DB::table('a_station')->where('pid', 0)->select('name', 'dev_num')->orderBy('dev_num','desc')->get()->toArray();
        $p0 = [
            'name'    => '作为顶级设备',
            'dev_num' => '/'
        ];
        $parents[] = (object)$p0;
        $parents = array_reverse($parents);
        return $parents;
    }
}
